package com.yehuishou.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.FormatFlagsConversionMismatchException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuishou.pojo.BackItem;
import com.yehuishou.pojo.Brand;
import com.yehuishou.pojo.Classify;
import com.yehuishou.pojo.Models;
import com.yehuishou.service.BrandService;
import com.yehuishou.service.ClassifyService;
import com.yehuishou.service.ModelService;

/*
 * @author xs
 * 商品品牌 分类 型号的控制器
 * 
 */

@Controller
public class ClassifyController {

	
	String rootPath = "/upload/";
	
	Map<String, Object> map  = new HashMap<>();
	List<BackItem> cbm = new ArrayList<>();

	@Autowired
	private ClassifyService classifyService;
	
	@Autowired
	
	private ModelService modelService;
	
	@Autowired

	private BrandService brandService;

	@RequestMapping("/content-1_5")
	public String getClassifyCbm(HttpServletRequest req, String npage, String classify,String brand,String model) {
		
		int page = 0;
		
		List<BackItem> cbm = new ArrayList<>();
		BackItem ba = new BackItem();
		
		if(brand!=null&&brand!="") {
			ba.setPid(Integer.parseInt(brand));
		}
		
		if(model!=null&&model!="") {
			ba.setModel(model);
			
		}
		
		if ((npage == null) || (npage == "")) {

			page = 1;
		} else {

			page = Integer.parseInt(npage);
		}

		if (classify != null && classify != "") {
		 int cid = Integer.parseInt(classify);
			
	        ba.setCid(cid);
		}
		
        PageHelper.startPage(page,10);
        
		cbm = classifyService.getAllcbm(ba);
		PageInfo<BackItem> pageinfo = new PageInfo<>(cbm);
		req.setAttribute("classifylist", classifyService.getAllClassify());
		if(classify!=null&&classify!="") {
			req.setAttribute("brandlist", brandService.getAllBrand(Integer.parseInt(classify)));
			}
		
		req.setAttribute("pageinfo", pageinfo);
		req.setAttribute("ba", ba);
		return "content-1_5";
	}
	@ResponseBody
	@RequestMapping("/deleteModels")
	public boolean deleteOneClassify(@Param(value = "mid")int mid) {
		modelService.deleteOne(mid);
		return true;
	}
	//添加商品的型号
	@RequestMapping("/addclassify")
	public String addclassify(HttpServletRequest req) {
		List<Classify> classifylist = classifyService.getAllClassify();
		
		req.setAttribute("brandlist", brandService.getAllBrand(classifylist.get(0).getCid()));
		req.setAttribute("classifylist", classifylist);
		return "classify_add";
	}
	
	
	//check classify exist
	@ResponseBody
	@RequestMapping("/checkClassifyname")
	public Map<String, Object> checkClassifyExsit(HttpServletRequest req,String classifyname){
		
		Classify classify = new Classify();
		  
		classify.setClassifyname(classifyname);
		boolean	 flag =classifyService.checkClassifyExist(classify);
		 System.out.println(flag);
		map.put("flag", flag);
		return map;
	}
	
	//添加分类
	@ResponseBody
	@RequestMapping("/addOneClassify")
	public Map<String, Object> addClassify(HttpServletRequest req,String classifyname){
		
		Classify classify = new Classify();
		classify.setClassifyname(classifyname);
		classifyService.addClassify(classify);
		map.put("classifys", classifyService.getAllClassify());
		return map;
	}
	
	
	
	@ResponseBody
	@RequestMapping("/checkBrandname")
	public Map<String, Object> checkBrandExsit(
			HttpServletRequest req,
			String brandname,
			Integer cid
			){
		
		Brand brand = new Brand();
		  
		brand.setBrandname(brandname);
		brand.setCid(cid);
		boolean	 flag =brandService.checkBrandExist(brand);
		 System.out.println(flag);
		map.put("flag", flag);
		return map;
	}
	
	
	@ResponseBody
	@RequestMapping("/addOneBrand")
	public boolean  brand(@RequestParam(defaultValue = "public") String model,Integer cid ,String brandname,
			//需要修改的商品的filepath
			@RequestParam(value="file") MultipartFile file) throws IllegalStateException, IOException {
		 
		Map<String, Object> map=new HashMap<>();
	          System.out.println(file);
			   if (file != null && !file.isEmpty()) {
					// 获取文件的原始名称
					String oldName = file.getOriginalFilename();
					// 获取文件大小
					// Long fileSize = file.getSize();
					// 获取文件的原始流
					// f.getInputStream()
					// 获取文件的类型
					// System.out.println(file.getContentType());

					// 组装文件存储路径
					String filePath = rootPath + model + File.separator;

					// 创建目录
					File f = new File(filePath);
					if (!f.exists()) {
						f.mkdirs();
					}
					// 生成一个新的不会重复的文件名
					// 1.获取后缀
					String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
					// 2.生成新的文件名
					String newFileName = UUID.randomUUID().toString() + "." + suffix;
					// 把上传的文件存储指定位置
					file.transferTo(new File(f, newFileName));// 文件上传操作
					String FilePath = rootPath + model + File.separator + newFileName;
                    Brand brand = new Brand();
                    brand.setBrandname(brandname);
                    brand.setCid(cid);
                    brand.setImg_url(FilePath.replace("\\", "/"));
					brandService.addBrand(brand);
				}
			   
				return true;
			   }

	//验证型号是否存在的ajax
	@ResponseBody
	@RequestMapping("/checkModelname")
	public Map<String, Object> checkModelname(
			HttpServletRequest req,
			String model,
			Integer pid
			){
		
		Models models = new Models();
		  
		models.setModel(model);
		models.setPid(pid);
	    boolean flag = modelService.checkModel(models);
		map.put("flag", flag);
		return map;
	}
	
	
	@ResponseBody
	@RequestMapping("/addOneModel")
	public Map<String, Object> addModelname(
			HttpServletRequest req,
			String model,
			Integer pid
			){
		
		Models models = new Models();
		  
		models.setModel(model);
		models.setPid(pid);
	    modelService.addModel(models);
		
		return map;
	}
	
	
	@RequestMapping("/viewbrand")
	public String addModelname(
			Integer cid,HttpServletRequest req
			){
		//根据cid查型号
		req.setAttribute("brs",brandService.getAllBrand(cid));
		return "brand_info";
	}
	
	
	//删除型号
	@ResponseBody
	@RequestMapping("/deletebrand")
	public boolean  deletebrand(
			Integer pid
			){
		
		boolean rs =true;
		brandService.deleteBrandById(pid);
		
		
		return rs;
	}
	
	
	@ResponseBody
	@RequestMapping("/checkModelExsit")
	public boolean checkModelExsit(
			Integer pid
			){
		boolean rs =true;
	   List<Models> mo= modelService.getModelByid(pid);
	   if(mo!=null&&mo.size()>0) {
		   rs=false;
		   
	   }
		
		return rs;
	}
	
	
	
	//检测该型号下面是否有商品包括（评估 回收  出售等等）
	@ResponseBody
	@RequestMapping("/checkmodelExsitItem")
	public boolean checkmodelExsitItem(
			Integer mid
			){
		Boolean rs = modelService.checkmodelExsitItem(mid);
		
		return rs;
	}
	
}
